package com.whz.iplocation.utils;

import lombok.experimental.UtilityClass;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * @author whz
 */
@UtilityClass
public class ToolUtils {

    public static long ipToNum(final String ipStr) {
        if (StringUtils.isEmpty(ipStr)) {
            return -1;
        }
        String[] arr = ipStr.split("\\.");
        long ip = (Long.parseLong(arr[0]) & 0xFFL) << 24 & 0xFF000000L;
        ip |= (Long.parseLong(arr[1]) & 0xFFL) << 16 & 0xFF0000L;
        ip |= (Long.parseLong(arr[2]) & 0xFFL) << 8 & 0xFF00L;
        ip |= (Long.parseLong(arr[3]) & 0xFFL);
        return ip;
    }

    public long read4ByteAsLong(final byte[] data, final int offset) {
        long val = data[offset] & 0xFF;
        val |= (data[offset + 1] << 8L) & 0xFF00L;
        val |= (data[offset + 2] << 16L) & 0xFF0000L;
        val |= (data[offset + 3] << 24L) & 0xFF000000L;
        return val;
    }

    public long read3ByteAsLong(final byte[] data, final int offset) {
        long val = data[offset] & 0xFFL;
        val |= (data[offset + 1] << 8) & 0xFF00L;
        val |= (data[offset + 2] << 16) & 0xFF0000L;
        return val;
    }

    public long convertToLong(String only4byteString) {
        if (StringUtils.isEmpty(only4byteString)) {
            return -1;
        }
        byte[] data = only4byteString.getBytes(StandardCharsets.UTF_8);
        if (data.length > 4) {
            return Integer.MAX_VALUE;
        }
        return read4ByteAsLong(data, 0);
    }
}